<template>
	<view>
		<!-- 滑动单元格 -->
		<van-swipe-cell :right-width="65" v-for="(item,index) in cart" :key="index">
			<!-- 商品卡片 -->
			<van-card :num="item.goods_number" :price="item.goods_price" desc="描述信息" :title="item.goods_name">
				<view slot="thumb" class="left">
					<van-checkbox :value="item.flag" @change="son(index)"></van-checkbox>
					<image :src="item.goods_img" style="width: 100%; height: 300rpx;"></image>
				</view>
				<view slot="footer">
					<van-stepper :value="item.buynum" @plus="addNum(index)" @minus="minus(index)" />
				</view>
			</van-card>
			<view slot="right" @click="del(index)">删除</view>
		</van-swipe-cell>

		<!-- SubmitBar 提交订单栏 -->
		<van-submit-bar :price="count*100" button-text="提交订单" @submit="place_order">
			<van-checkbox :value="flags" @change="all"></van-checkbox>
		</van-submit-bar>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				cart: wx.getStorageSync('cart') || [],
				flags: true
			};
		},
		methods: {
			//点击删除按钮
			del(ind) {
				this.cart.splice(ind, 1)
				wx.setStorageSync('cart', this.cart)
			},
			//点击全选
			all() {
				this.flags = !this.flags
				if (this.flags) {
					this.cart.forEach(item => {
						item.flag = true
					})
				} else {
					this.cart.forEach(item => {
						item.flag = false
					})
				}
				wx.setStorageSync('cart', this.cart)
			},
			//反选
			son(ind) {
				this.cart[ind].flag = !this.cart[ind].flag
				this.change()
				wx.setStorageSync('cart', this.cart)
			},
			// 封装change,实现反选
			change() {
				// 商品数量
				var count = 0
				this.cart.forEach(item => {
					if (item.flag) {
						count++
					}
				})
				if (count == this.cart.length) {
					this.flags = true
				} else {
					this.flags = false
				}
			},
			
			//点击减号
			addNum(ind) {
				console.log(111)
				this.cart[ind].buynum += 1
				wx.setStorageSync('cart', this.cart)
			},
			//点击加号
			minus(ind) {
				this.cart[ind].buynum -= 1
				wx.setStorageSync('cart', this.cart)
			},

			// 提交订单
			place_order() {
				if (this.address.length == 0) {
					wx.showToast({
						title: "选择收货地址",
						icon: 'error',
					})
					return
				}
				if (this.num_check == 0) {
					wx.showToast({
						title: "选购商品",
						icon: 'error',
					})
					return
				}
				wx.navigateTo({
					url: '../pay/pay'
				});
			}
		},
		computed: {
			count() {
				var sum = 0
				if (!this.cart) {
					return false
				}
				this.cart.forEach(item => {
					console.log(item, '23')
					if (item.flag == true) {
						sum += item.goods_price * item.buynum
					}
				})
				return sum
			}
		},
		onLoad() {
			this.change()
		}
	}
</script>

<style lang="scss">
	.left {
		display: flex;
		align-items: center;
	}
</style>
